﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace SimpleCrawler
{
    public partial class Form1 : Form
    {
        BindingSource resultbindingSource = new BindingSource();
        SimpleCrawler mycrawler = new SimpleCrawler();
        Thread thread = null;
        public Form1()
        {
            InitializeComponent();
            resultView.DataSource = resultbindingSource;
            //  mycrawler.PageDownloaded+= 
            mycrawler.PageDownloaded += Page_Downloaded;
            mycrawler.CrawlerStopped += Crawler_Stopped;
        }
      
        private void Crawler_Stopped(SimpleCrawler obj)
        {
            Action action = () => Info.Text = "爬虫已停止!";

            if (this.InvokeRequired)
            {
                this.Invoke(action);
            }
            else
            {
                action();
            }
        }

        private void Page_Downloaded(SimpleCrawler crawler, string url, string info)
        {
            var pageInfo = new 
            { 
                No = resultbindingSource.Count + 1,
                Url = url, 
                Status = info 
            };

            Action action = () => { resultbindingSource.Add(pageInfo); };

            if (this.InvokeRequired)
            {
                this.Invoke(action);
            }
            else
            {
                action();
            }
        }

       

        private void OK_Click(object sender, EventArgs e)
        {
            resultbindingSource.Clear();
            mycrawler.StartURL = TOtext.Text;
            
            Match match = Regex.Match(mycrawler.StartURL, SimpleCrawler.urlParseRegex);
            if (match.Length == 0) 
                return;
            string host = match.Groups["host"].Value;

            mycrawler.HostFilter = "^" + host + "$";
            mycrawler.FileFilter = ".html?$";

            if (thread != null)
            {
                thread.Abort();
            }
            thread = new Thread(mycrawler.Start);
            thread.Start();
           Info.Text = "开始爬行！....";
        }
         private void Form1_Load(object sender, EventArgs e)
        {

        }
        private void resultView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
